<?php
require_once __DIR__ . '/../functions.php';

// 检查管理员权限
if (!isAdmin()) {
    redirect('../index.php', '您没有权限访问此页面', 'danger');
}

$results = [];
$uploadedFile = null;
$settlementMode = 'principal'; // 默认结本金模式

// 使用SESSION保存查询结果，避免页面刷新丢失
if (isset($_GET['clear']) && $_GET['clear'] == '1') {
    unset($_SESSION['batch_settlement_results']);
    unset($_SESSION['batch_settlement_file']);
    unset($_SESSION['batch_settlement_mode']);
    header('Location: batch_settlement.php');
    exit;
}

// 如果有保存的查询结果，优先使用
if (isset($_SESSION['batch_settlement_results']) && !isset($_POST['action'])) {
    $results = $_SESSION['batch_settlement_results'];
    $uploadedFile = $_SESSION['batch_settlement_file'] ?? null;
    $settlementMode = $_SESSION['batch_settlement_mode'] ?? 'principal';
}

// 处理文件上传和查询
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] == 'process_settlement') {
    if (!isset($_FILES['settlement_file']) || $_FILES['settlement_file']['error'] !== UPLOAD_ERR_OK) {
        $error = '请选择要上传的文件';
    } else {
        $file = $_FILES['settlement_file'];
        $uploadedFile = $file['name'];
        $settlementMode = $_POST['settlement_mode'] ?? 'principal';
        
        // 检查文件类型
        $allowedTypes = ['text/plain', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'text/csv'];
        $fileExtension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        
        if (!in_array($file['type'], $allowedTypes) && !in_array($fileExtension, ['txt', 'csv', 'xls', 'xlsx'])) {
            $error = '不支持的文件类型，请上传 TXT、CSV 或 Excel 文件';
        } else {
            try {
                $settlementData = [];
                
                if ($fileExtension == 'txt' || $fileExtension == 'csv') {
                    // 处理文本文件
                    $content = file_get_contents($file['tmp_name']);
                    $lines = explode("\n", $content);
                    
                    foreach ($lines as $line) {
                        $line = trim($line);
                        if (!empty($line)) {
                            if (strpos($line, '----') !== false) {
                                // 使用----分隔符
                                $parts = explode('----', $line);
                                $trackingNo = trim($parts[0]);
                                $amount = isset($parts[1]) ? trim($parts[1]) : '';
                            } else {
                                // 使用逗号分隔
                                $parts = explode(',', $line);
                                $trackingNo = trim($parts[0]);
                                $amount = isset($parts[1]) ? trim($parts[1]) : '';
                            }
                            
                            if (!empty($trackingNo)) {
                                $settlementData[] = [
                                    'tracking_no' => $trackingNo,
                                    'amount' => $amount
                                ];
                            }
                        }
                    }
                } elseif (in_array($fileExtension, ['xls', 'xlsx'])) {
                    // 处理Excel文件
                    require_once __DIR__ . '/../vendor/autoload.php';
                    
                    $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file['tmp_name']);
                    $worksheet = $spreadsheet->getActiveSheet();
                    
                    foreach ($worksheet->getRowIterator() as $row) {
                        $cellIterator = $row->getCellIterator();
                        $cellIterator->setIterateOnlyExistingCells(false);
                        
                        $rowData = [];
                        foreach ($cellIterator as $cell) {
                            $rowData[] = trim($cell->getValue());
                        }
                        
                        if (!empty($rowData[0])) {
                            $settlementData[] = [
                                'tracking_no' => $rowData[0],
                                'amount' => $rowData[1] ?? ''
                            ];
                        }
                    }
                }
                
                if (empty($settlementData)) {
                    $error = '文件中没有找到有效的物流单号';
                } else {
                    // 查询订单并处理结算
                    $db = getDB();
                    $processedCount = 0;
                    
                    foreach ($settlementData as $item) {
                        $trackingNo = $item['tracking_no'];
                        $amount = $item['amount'];
                        
                        $stmt = $db->prepare("SELECT o.*, u.username, u.phone, u.group_name FROM orders o 
                                           LEFT JOIN users u ON o.user_id = u.id 
                                           WHERE o.tracking_no = ?");
                        $stmt->execute([$trackingNo]);
                        $order = $stmt->fetch();
                        
                        if ($order) {
                            // 计算结算金额
                            $settlementAmount = null;
                            $shouldProcess = true; // 标记是否处理该订单
                            
                            if (!empty($amount) && is_numeric($amount)) {
                                $settlementAmount = floatval($amount);
                            } else {
                                if ($settlementMode == 'principal') {
                                    // 结本金模式：金额为空时按下单金额结本金
                                    $settlementAmount = $order['order_amount'];
                                } else {
                                    // 结本金+佣金模式：金额为空时不结算
                                    $shouldProcess = false;
                                    $settlementAmount = null;
                                }
                            }
                            
                            $order['delivery_location_label'] = getConfigOptionLabel('delivery_location', $order['delivery_location']);
                            $order['order_platform_label'] = getConfigOptionLabel('order_platform', $order['order_platform']);
                            $order['payment_method_label'] = getPaymentMethodText($order['payment_method']);
                            
                            $results[] = [
                                'tracking_no' => $trackingNo,
                                'found' => true,
                                'order' => $order,
                                'settlement_amount' => $settlementAmount,
                                'settlement_mode' => $settlementMode,
                                'should_process' => $shouldProcess,
                                'processed' => false,
                                'message' => $shouldProcess ? '待处理' : '跳过（金额为空）'
                            ];
                        } else {
                            $results[] = [
                                'tracking_no' => $trackingNo,
                                'found' => false,
                                'order' => null,
                                'settlement_amount' => null,
                                'should_process' => false,
                                'processed' => false,
                                'message' => '订单不存在'
                            ];
                        }
                    }
                    
                    // 保存查询结果到SESSION
                    $_SESSION['batch_settlement_results'] = $results;
                    $_SESSION['batch_settlement_file'] = $uploadedFile;
                    $_SESSION['batch_settlement_mode'] = $settlementMode;
                    
                    $success = '文件解析完成，共处理 ' . count($settlementData) . ' 个物流单号，请点击"开始结算"按钮进行批量结算';
                }
            } catch (Exception $e) {
                $error = '文件处理失败：' . $e->getMessage();
            }
        }
    }
}

// 防重复提交token
if (!isset($_SESSION['form_tokens'])) {
    $_SESSION['form_tokens'] = [];
}

// 生成新的token
$currentToken = md5(uniqid(mt_rand(), true) . $_SERVER['REMOTE_ADDR']);
$_SESSION['form_tokens'][] = $currentToken;
// 保持最近50个token
if (count($_SESSION['form_tokens']) > 200) {
    array_shift($_SESSION['form_tokens']);
}

include __DIR__ . '/header.php';
?>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">批量结算</h1>
    <?php if (!empty($results)): ?>
        <div class="btn-group">
            <a href="batch_settlement.php?clear=1" class="btn btn-warning">
                <i class="bi bi-trash"></i> 清除数据
            </a>
        </div>
    <?php endif; ?>
</div>

<?php if (isset($error)): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="bi bi-exclamation-triangle-fill"></i> <?php echo htmlspecialchars($error); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<?php if (isset($success)): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="bi bi-check-circle-fill"></i> <?php echo htmlspecialchars($success); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<!-- 上传表单 -->
<div class="card mb-4">
    <div class="card-header bg-primary text-white">
        <h5 class="mb-0">
            <i class="bi bi-upload"></i> 上传结算文件
        </h5>
    </div>
    <div class="card-body">
        <form method="POST" enctype="multipart/form-data" class="needs-validation" novalidate id="uploadForm">
            <input type="hidden" name="action" value="process_settlement">
            
            <div class="row">
                <div class="col-md-6">
                    <div class="mb-3">
                        <label for="settlement_mode" class="form-label">
                            <i class="bi bi-gear"></i> 结算模式 <span class="text-danger">*</span>
                        </label>
                        <select class="form-select" id="settlement_mode" name="settlement_mode" required>
                            <option value="principal" <?php echo $settlementMode == 'principal' ? 'selected' : ''; ?>>结本金</option>
                            <option value="principal_commission" <?php echo $settlementMode == 'principal_commission' ? 'selected' : ''; ?>>结本金+佣金</option>
                        </select>
                        <div class="form-text">选择批量结算的模式</div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="mb-3">
                        <label for="settlement_file" class="form-label">
                            <i class="bi bi-file-earmark-text"></i> 选择文件 <span class="text-danger">*</span>
                        </label>
                        <input type="file" class="form-control" id="settlement_file" name="settlement_file" 
                               accept=".txt,.csv,.xls,.xlsx" required>
                        <div class="form-text">
                            支持的文件格式：TXT、CSV、Excel（.xls、.xlsx）
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="mb-3">
                <div class="alert alert-info">
                    <i class="bi bi-info-circle"></i>
                    <strong>使用说明：</strong>
                    <ul class="mb-0 mt-2">
                        <li><strong>文件格式说明：</strong>
                            <ul>
                                <li>表格文件：第一列为快递单号，第二列为金额</li>
                                <li>TXT/CSV文件：使用逗号分隔或"----"分隔，格式：快递单号,金额 或 快递单号----金额</li>
                                <li>Excel文件：第一列为快递单号，第二列为金额</li>
                            </ul>
                        </li>
                        <li><strong>结本金模式：</strong>
                            <ul>
                                <li>如果金额为空，则自动按下单金额结本金</li>
                                <li>示例：SF1234567890,100.00 或 SF1234567890----100.00</li>
                            </ul>
                        </li>
                        <li><strong>结本金+佣金模式：</strong>
                            <ul>
                                <li>如果金额为空，则不结算该订单</li>
                                <li>示例：SF1234567890,110.00 或 SF1234567890----110.00</li>
                            </ul>
                        </li>
                        <li>系统会自动匹配数据库中的订单信息并进行结算</li>
                        <li>结算操作会记录到订单操作记录中</li>
                        <li>结算金额会汇总到用户的待结账单中</li>
                    </ul>
                </div>
            </div>
            
            <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                <button type="submit" class="btn btn-primary">
                    <i class="bi bi-upload"></i> 上传并解析文件
                </button>
                <button type="button" class="btn btn-secondary" onclick="downloadTemplate()">
                    <i class="bi bi-download"></i> 下载模板
                </button>
            </div>
        </form>
    </div>
</div>

<!-- 结算进度和结果 -->
<?php if (!empty($results)): ?>
    <div class="card">
        <div class="card-header bg-success text-white d-flex justify-content-between align-items-center">
            <h5 class="mb-0">
                <i class="bi bi-list-check"></i> 结算数据
                <?php if ($uploadedFile): ?>
                    <small class="text-light">(文件：<?php echo htmlspecialchars($uploadedFile); ?>, 模式：<?php echo $settlementMode == 'principal' ? '结本金' : '结本金+佣金'; ?>)</small>
                <?php endif; ?>
            </h5>
            <button type="button" class="btn btn-light btn-sm" onclick="startBatchSettlement()" id="startSettlementBtn">
                <i class="bi bi-play-circle"></i> 开始结算
            </button>
        </div>
        <div class="card-body">
            <?php
            $foundCount = count(array_filter($results, function($r) { return $r['found']; }));
            $notFoundCount = count(array_filter($results, function($r) { return !$r['found']; }));
            $processedCount = count(array_filter($results, function($r) { return $r['processed']; }));
            $shouldProcessCount = count(array_filter($results, function($r) { return $r['found'] && $r['should_process']; }));
            ?>
            
            <!-- 进度条 -->
            <div class="mb-4" id="progressSection" style="display: none;">
                <div class="d-flex justify-content-between mb-2">
                    <span>处理进度</span>
                    <span id="progressText">0/<?php echo $shouldProcessCount; ?></span>
                </div>
                <div class="progress" style="height: 20px;">
                    <div id="progressBar" class="progress-bar progress-bar-striped progress-bar-animated" 
                         role="progressbar" style="width: 0%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
                    </div>
                </div>
                <div class="mt-2 text-center">
                    <button type="button" class="btn btn-warning btn-sm" onclick="stopProcessing()" id="stopBtn">
                        <i class="bi bi-stop-circle"></i> 停止处理
                    </button>
                </div>
            </div>
            
            <div class="row mb-4">
                <div class="col-md-2">
                    <div class="card bg-success text-white">
                        <div class="card-body text-center">
                            <h6 class="card-title">已找到</h6>
                            <h3 class="mb-0"><?php echo $foundCount; ?></h3>
                        </div>
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="card bg-warning text-white">
                        <div class="card-body text-center">
                            <h6 class="card-title">未找到</h6>
                            <h3 class="mb-0"><?php echo $notFoundCount; ?></h3>
                        </div>
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="card bg-info text-white">
                        <div class="card-body text-center">
                            <h6 class="card-title">待处理</h6>
                            <h3 class="mb-0" id="shouldProcessCount"><?php echo $shouldProcessCount; ?></h3>
                        </div>
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="card bg-primary text-white">
                        <div class="card-body text-center">
                            <h6 class="card-title">已处理</h6>
                            <h3 class="mb-0" id="processedCount"><?php echo $processedCount; ?></h3>
                        </div>
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="card bg-secondary text-white">
                        <div class="card-body text-center">
                            <h6 class="card-title">跳过</h6>
                            <h3 class="mb-0"><?php echo $foundCount - $shouldProcessCount; ?></h3>
                        </div>
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="card bg-primary text-white">
                        <div class="card-body text-center">
                            <h6 class="card-title">成功率</h6>
                            <h3 class="mb-0"><?php echo count($results) > 0 ? round($foundCount / count($results) * 100) : 0; ?>%</h3>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 实时日志 -->
            <div class="mb-3">
                <div class="card">
                    <div class="card-header bg-light">
                        <h6 class="mb-0">处理日志</h6>
                    </div>
                    <div class="card-body">
                        <div id="processLog" class="border rounded p-3 bg-light" style="max-height: 200px; overflow-y: auto; font-family: monospace; font-size: 0.875rem;">
                            <?php foreach ($results as $result): ?>
                                <?php if ($result['found']): ?>
                                    <div class="log-entry" data-tracking="<?php echo $result['tracking_no']; ?>">
                                        <?php echo date('H:i:s'); ?> - <?php echo $result['tracking_no']; ?>: <?php echo $result['message']; ?>
                                    </div>
                                <?php endif; ?>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>物流单号</th>
                            <th>登记</th>
                            <th>订单ID</th>
                            <th>商品名称</th>
                            <th>收货地</th>
                            <th>下单平台</th>
                            <th>用户</th>
                            <th>下单金额</th>
                            <th>本次结算金额</th>
                            <th>付款方式</th>
                            <th id="settlement-type-header">结算类型</th>
                            <th>退还</th>
                            <th>签收</th>
                            <th id="status-header">状态</th>
                            <th>处理状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="resultsTableBody">
                        <?php foreach ($results as $index => $result): ?>
                            <tr class="<?php 
                                if (!$result['found']) echo 'table-warning';
                                elseif (!$result['should_process']) echo 'table-secondary';
                                elseif ($result['processed']) echo 'table-success';
                                else echo 'table-info';
                            ?>" 
                                id="row-<?php echo $result['found'] ? $result['order']['id'] : 'notfound-'.$index; ?>">
                                <td class="fw-bold"><?php echo htmlspecialchars($result['tracking_no']); ?></td>
                                <td>
                                    <?php if ($result['found']): ?>
                                        <span class="badge bg-success">已找到</span>
                                    <?php else: ?>
                                        <span class="badge bg-warning">未找到</span>
                                    <?php endif; ?>
                                </td>
                                <?php if ($result['found']): ?>
                                    <?php $order = $result['order']; ?>
                                    <td><?php echo $order['id']; ?></td>
                                    <td><?php echo htmlspecialchars($order['product_name']); ?></td>
                                    <td><?php echo htmlspecialchars($order['delivery_location_label']); ?></td>
                                    <td><?php echo htmlspecialchars($order['order_platform_label']); ?></td>
                                    <td><?php echo htmlspecialchars($order['username']); ?></td>
                                    <td><?php echo formatAmount($order['order_amount']); ?></td>
                                    <td id="settlement-amount-<?php echo $order['id']; ?>" class="fw-bold text-success">
                                        <?php if ($result['settlement_amount'] !== null): ?>
                                            <?php echo formatAmount($result['settlement_amount']); ?>
                                        <?php else: ?>
                                            <span class="text-muted">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <span class="badge bg-<?php echo $order['payment_method'] == 'group_paid' ? 'warning' : 'info'; ?>">
                                            <?php echo $order['payment_method_label']; ?>
                                        </span>
                                    </td>
                                    <td id="settlement-type-<?php echo $order['id']; ?>">
                                        <span class="badge bg-<?php echo getSettlementTypeClass($order['settlement_type']); ?>">
                                            <?php echo getSettlementTypeText($order['settlement_type']); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <span class="badge bg-<?php echo getOrderReturnClass($order['is_returned']); ?>">
                                            <?php echo getOrderReturnText($order['is_returned']); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <span class="badge bg-<?php echo getOrderSignClass($order['is_signed']); ?>">
                                            <?php echo getOrderSignText($order['is_signed']); ?>
                                        </span>
                                    </td>
                                    <td id="status-<?php echo $order['id']; ?>">
                                        <span class="badge bg-<?php echo getOrderStatusClass($order['status']); ?>">
                                            <?php echo getOrderStatusText($order['status']); ?>
                                        </span>
                                    </td>
                                    <td id="process-status-<?php echo $order['id']; ?>">
                                        <?php if (!$result['should_process']): ?>
                                            <span class="badge bg-secondary">跳过</span>
                                        <?php elseif ($result['processed']): ?>
                                            <span class="badge bg-success">已结算</span>
                                        <?php else: ?>
                                            <span class="badge bg-warning">待处理</span>
                                        <?php endif; ?>
                                    </td>
                                    <td id="actions-<?php echo $order['id']; ?>">
                                        <div class="btn-group" role="group">
                                            <button type="button" class="btn btn-sm btn-outline-primary" 
                                                    onclick="showOrderDetails(<?php echo $order['id']; ?>)"
                                                    data-bs-toggle="tooltip" title="查看详情">
                                                <i class="bi bi-eye"></i>
                                            </button>
                                            
                                            <button type="button" class="btn btn-sm btn-outline-success" 
                                                    onclick="editOrder(<?php echo $order['id']; ?>)"
                                                    data-bs-toggle="tooltip" title="处理订单">
                                                <i class="bi bi-pencil"></i>
                                            </button>
                                            
                                            <?php if ($order['order_screenshot']): ?>
                                                <button type="button" class="btn btn-sm btn-outline-info" 
                                                        onclick="showImageModal('<?php echo UPLOAD_URL . 'orders/' . $order['order_screenshot']; ?>')"
                                                        data-bs-toggle="tooltip" title="订单截图">
                                                    <i class="bi bi-image"></i>
                                                </button>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                <?php else: ?>
                                    <td colspan="15" class="text-center text-muted">
                                        <i class="bi bi-x-circle"></i> 未找到对应的订单
                                    </td>
                                <?php endif; ?>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            
            <div class="mt-3">
                <button type="button" class="btn btn-primary" onclick="exportResults()">
                    <i class="bi bi-download"></i> 导出处理结果
                </button>
                <a href="batch_settlement.php?clear=1" class="btn btn-warning">
                    <i class="bi bi-trash"></i> 清除数据
                </a>
            </div>
        </div>
    </div>
<?php endif; ?>

<!-- 订单详情模态框 -->
<div class="modal fade" id="orderDetailsModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">订单详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="orderDetailsContent">
                <!-- 详情内容将通过AJAX加载 -->
            </div>
        </div>
    </div>
</div>

<!-- 编辑订单模态框 -->
<div class="modal fade" id="editOrderModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">处理订单</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="editOrderContent">
                <!-- 编辑内容将通过AJAX加载 -->
            </div>
        </div>
    </div>
</div>

<!-- 图片放大模态框 -->
<div class="modal fade" id="imageModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">图片预览</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body text-center">
                <img id="modalImage" src="" class="img-fluid" style="max-height: 80vh;">
            </div>
        </div>
    </div>
</div>

<?php include __DIR__ . '/footer.php'; ?>

<script>
let isProcessing = false;
let currentIndex = 0;
let totalOrders = 0;
let processedOrders = 0;
let processingInterval = null;

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    totalOrders = <?php echo $shouldProcessCount; ?>;
    processedOrders = <?php echo $processedCount; ?>;
    
    // 如果还有未处理的订单，显示开始结算按钮
    if (totalOrders > 0 && processedOrders < totalOrders) {
        document.getElementById('startSettlementBtn').style.display = 'block';
    }
});

// 开始批量结算
function startBatchSettlement() {
    if (isProcessing) {
        showToast('正在处理中，请稍候...', 'warning');
        return;
    }
    
    if (totalOrders === 0) {
        showToast('没有找到可处理的订单', 'warning');
        return;
    }
    
    if (processedOrders >= totalOrders) {
        showToast('所有订单已处理完成', 'info');
        return;
    }
    
    // 显示进度条
    document.getElementById('progressSection').style.display = 'block';
    document.getElementById('startSettlementBtn').disabled = true;
    
    isProcessing = true;
    currentIndex = 0;
    
    // 开始处理
    processNextOrder();
}

// 处理下一个订单
function processNextOrder() {
    if (!isProcessing || currentIndex >= totalOrders) {
        finishProcessing();
        return;
    }
    
    const orders = <?php echo json_encode(array_values(array_filter($results, function($r) { return $r['found'] && $r['should_process']; }))); ?>;
    
    if (currentIndex >= orders.length) {
        finishProcessing();
        return;
    }
    
    const order = orders[currentIndex];
    
    // 如果订单已处理，跳过
    if (order.processed) {
        currentIndex++;
        updateProgress();
        processNextOrder();
        return;
    }
    
    // 更新日志
    addLog(`${order.tracking_no}: 开始处理...`);
    
    // 发送结算请求
    const formData = new FormData();
    formData.append('action', 'settle_single');
    formData.append('order_id', order.order.id);
    
    // 使用正确的结算类型映射
    let settlementType = order.settlement_mode;
    if (settlementType === 'principal') {
        settlementType = 'commission';
    }
    formData.append('settlement_type', settlementType);
    
    formData.append('settlement_amount', order.settlement_amount || '');
    formData.append('settlement_info', '无');
    
    console.log('结算参数:', {
        orderId: order.order.id,
        settlementType: settlementType,
        settlementAmount: order.settlement_amount
    });

    fetch('api/batch_settlement_process.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        console.log('服务器响应:', data);
        
        if (data.success) {
            // 更新界面，传递完整的结算数据
            updateOrderStatus(order.order.id, true, '结算成功', {
                settlement_type: order.settlement_mode,
                settlement_amount: data.amount || order.settlement_amount
            });
            addLog(`${order.tracking_no}: 结算成功 - ${data.message}`);
            processedOrders++;
        } else {
            updateOrderStatus(order.order.id, false, data.message);
            addLog(`${order.tracking_no}: 结算失败 - ${data.message}`);
            console.error('结算失败详情:', data);
        }
        
        currentIndex++;
        updateProgress();
        
        // 继续处理下一个订单
        setTimeout(processNextOrder, 500);
        
    })
    .catch(error => {
        console.error('请求错误:', error);
        updateOrderStatus(order.order.id, false, '请求失败: ' + error.message);
        addLog(`${order.tracking_no}: 请求失败 - ${error.message}`);
        
        currentIndex++;
        updateProgress();
        setTimeout(processNextOrder, 500);
    });
}

// 更新进度
function updateProgress() {
    const progress = Math.round((currentIndex / totalOrders) * 100);
    document.getElementById('progressBar').style.width = progress + '%';
    document.getElementById('progressBar').setAttribute('aria-valuenow', progress);
    document.getElementById('progressText').textContent = `${currentIndex}/${totalOrders}`;
    document.getElementById('processedCount').textContent = processedOrders;
}

// 更新订单状态和信息
function updateOrderStatus(orderId, success, message, settlementData) {
    const statusCell = document.getElementById(`process-status-${orderId}`);
    const row = document.getElementById(`row-${orderId}`);
    
    if (success) {
        statusCell.innerHTML = '<span class="badge bg-success">已结算</span>';
        row.classList.remove('table-info');
        row.classList.add('table-success');
        
        // 更新订单状态
        const orderStatusCell = document.getElementById(`status-${orderId}`);
        if (orderStatusCell) {
            orderStatusCell.innerHTML = '<span class="badge bg-success">已结算</span>';
        }
        
        // 更新结算类型
        const settlementTypeCell = document.getElementById(`settlement-type-${orderId}`);
        if (settlementTypeCell) {
            const settlementType = settlementData?.settlement_type || 'principal_commission';
            const typeText = settlementType === 'principal' ? '结本金' : '结本金+佣金';
            const typeClass = settlementType === 'principal' ? 'info' : 'primary';
            settlementTypeCell.innerHTML = `<span class="badge bg-${typeClass}">${typeText}</span>`;
        }
        
        // 更新结算金额显示
        const settlementAmountCell = document.getElementById(`settlement-amount-${orderId}`);
        if (settlementAmountCell && settlementData?.settlement_amount) {
            settlementAmountCell.innerHTML = formatAmount(settlementData.settlement_amount);
        }
        
    } else {
        statusCell.innerHTML = `<span class="badge bg-danger">失败</span><br><small>${message}</small>`;
        row.classList.remove('table-info');
        row.classList.add('table-danger');
    }
}

// 添加日志
function addLog(message) {
    const logContainer = document.getElementById('processLog');
    const logEntry = document.createElement('div');
    logEntry.className = 'log-entry';
    logEntry.innerHTML = `${new Date().toLocaleTimeString()} - ${message}`;
    logContainer.appendChild(logEntry);
    logContainer.scrollTop = logContainer.scrollHeight;
}

// 停止处理
function stopProcessing() {
    isProcessing = false;
    finishProcessing();
    addLog('处理已停止');
}

// 完成处理
function finishProcessing() {
    isProcessing = false;
    document.getElementById('startSettlementBtn').disabled = false;
    document.getElementById('stopBtn').style.display = 'none';
    
    if (processedOrders >= totalOrders) {
        addLog('所有订单处理完成！');
        showToast('批量结算完成！', 'success');
    } else {
        addLog('处理已停止');
        showToast('处理已停止', 'warning');
    }
}

// 下载模板 - 修复函数
function downloadTemplate() {
    const settlementMode = document.getElementById('settlement_mode').value;
    let templateContent = '';
    
    if (settlementMode === 'principal') {
        templateContent = `物流单号,金额（结本金模式：金额为空则按下单金额结算）
SF1234567890,100.00
SF1234567891,
SF1234567892,150.50`;
    } else {
        templateContent = `物流单号,金额（结本金+佣金模式：金额为空则不结算）
SF1234567890,110.00
SF1234567891,
SF1234567892,165.55`;
    }
    
    // 创建Blob并下载
    const blob = new Blob([templateContent], { type: 'text/plain;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `批量结算模板_${settlementMode === 'principal' ? '结本金' : '结本金加佣金'}.csv`;
    
    // 触发下载
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    // 清理URL
    setTimeout(() => {
        URL.revokeObjectURL(url);
    }, 100);
    
    showToast('模板下载成功', 'success');
}

// 导出结果 - 修复乱码问题
function exportResults() {
    <?php if (!empty($results)): ?>
        // 使用 UTF-8 BOM 解决 Excel 中文乱码问题
        let csvContent = "\uFEFF";
        csvContent += "物流单号,查询状态,订单ID,商品名称,收货地,下单平台,用户,下单金额,本次结算金额,付款方式,结算类型,退还状态,签收状态,订单状态,处理状态,处理信息\n";
        
        <?php foreach ($results as $result): ?>
            <?php if ($result['found']): ?>
                <?php $order = $result['order']; ?>
                csvContent += "<?php echo $result['tracking_no']; ?>,已找到,<?php echo $order['id']; ?>,<?php echo $order['product_name']; ?>,<?php echo $order['delivery_location_label']; ?>,<?php echo $order['order_platform_label']; ?>,<?php echo $order['username']; ?>,<?php echo $order['order_amount']; ?>,<?php echo $result['settlement_amount'] ?? ''; ?>,<?php echo $order['payment_method_label']; ?>,<?php echo getSettlementTypeText($order['settlement_type']); ?>,<?php echo getOrderReturnText($order['is_returned']); ?>,<?php echo getOrderSignText($order['is_signed']); ?>,<?php echo getOrderStatusText($order['status']); ?>,<?php 
                    if (!$result['should_process']) echo '跳过';
                    elseif ($result['processed']) echo '已处理';
                    else echo '未处理';
                ?>,<?php echo $result['message']; ?>\n";
            <?php else: ?>
                csvContent += "<?php echo $result['tracking_no']; ?>,未找到,,,,,,,,,,,,未处理,<?php echo $result['message']; ?>\n";
            <?php endif; ?>
        <?php endforeach; ?>
        
        // 使用正确的编码创建 Blob
        const blob = new Blob([csvContent], { 
            type: 'text/csv;charset=utf-8;' 
        });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = '批量结算结果_<?php echo date('Ymd_His'); ?>.csv';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
    <?php else: ?>
        showToast('没有处理结果可以导出', 'warning');
    <?php endif; ?>
}

// 以下函数与批量查询页面相同
function showOrderDetails(orderId) {
    // 显示加载状态
    document.getElementById('orderDetailsContent').innerHTML = `
        <div class="text-center py-5">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <p class="mt-3">加载中...</p>
        </div>
    `;
    
    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('orderDetailsModal'));
    modal.show();
    
    // 加载订单详情
    fetch('/api/order_details.php?id=' + orderId)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 显示订单详情...
            } else {
                document.getElementById('orderDetailsContent').innerHTML = `
                    <div class="alert alert-danger">${data.message || '加载失败'}</div>
                `;
            }
        })
        .catch(error => {
            document.getElementById('orderDetailsContent').innerHTML = `
                <div class="alert alert-danger">加载失败：${error.message}</div>
            `;
        });
}

function editOrder(orderId) {
    // 显示加载状态
    document.getElementById('editOrderContent').innerHTML = `
        <div class="text-center py-5">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <p class="mt-3">加载中...</p>
        </div>
    `;
    
    // 显示模态框
    const modalElement = document.getElementById('editOrderModal');
    const modal = new bootstrap.Modal(modalElement);
    modal.show();
    
    // 加载订单编辑表单
    fetch('api/order_edit_form_new.php?id=' + orderId)
        .then(response => response.text())
        .then(html => {
            document.getElementById('editOrderContent').innerHTML = html;
        })
        .catch(error => {
            document.getElementById('editOrderContent').innerHTML = `
                <div class="alert alert-danger">加载失败：${error.message}</div>
            `;
        });
}

function showImageModal(imageUrl) {
    document.getElementById('modalImage').src = imageUrl;
    const modal = new bootstrap.Modal(document.getElementById('imageModal'));
    modal.show();
}

// 格式化金额
function formatAmount(amount) {
    return '¥' + parseFloat(amount).toFixed(2);
}

// 初始化工具提示
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
    return new bootstrap.Tooltip(tooltipTriggerEl);
});
</script>